package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TGoods;
import com.ruoyi.system.domain.TestCourse;
import com.ruoyi.system.mapper.TGoodsMapper;
import com.ruoyi.system.service.TGoodsService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.UUID;

@Service
public class TGoodsServiceImpl implements TGoodsService {

    @Autowired
    private TGoodsMapper goodsMapper;
    @Override
    public List<TGoods> selectGoodsList(TGoods goods) {
        return goodsMapper.selectGoodsList(goods);
    }

    @Override
    public List<TGoods> selectGoodsAll() {
        return goodsMapper.selectGoodsAll();
    }

    @Override
    public TGoods selectGoodsById(Long goodsId) {
        return goodsMapper.selectGoodsById(goodsId);
    }

    /*名称校验*/
    @Override
    public boolean checkGoodsNameUnique(TGoods goods) {
        Long goodsId = StringUtils.isNull(goods.getGoodsId()) ? -1L : goods.getGoodsId();
        TGoods info = goodsMapper.checkGoodsNameUnique(goods.getGoodsName());
        if (StringUtils.isNotNull(info) && info.getGoodsId().longValue() != goodsId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }



    @Override
    public int deleteGoodsById(Long goodsId) {
        return goodsMapper.deleteGoodsById(goodsId);
    }

    @Override
    public int deleteGoodsByIds(Long[] goodsIds) {
        return goodsMapper.deleteGoodsByIds(goodsIds);
    }



    @Override
    public int insertGoods(TGoods goods) {
        /*// 1. 创建存储目录（如果不存在）
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 2. 上传图片
        if (file != null && !file.isEmpty()) {
            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + "." +
                    FilenameUtils.getExtension(file.getOriginalFilename());

            // 构建完整路径
            Path filePath = Paths.get(uploadPath, fileName);

            // 保存文件
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 设置相对路径（只存储文件名）
            goods.setImage(fileName);
        }*/

        return goodsMapper.insertGoods(goods);
    }

    @Override
    public int updateGoods(TGoods goods) {
        return goodsMapper.updateGoods(goods);
    }
}
